app.controller('ProfileCtrl', ['$scope', '$q', '$timeout', 'apiService',
    function(scope, $q, $timeout, apiService) {
	scope.tabIndex = 1;
	scope.member = {birthyear:0, birthmonth:0, birthday:0};
	scope.years = dateUtils.getYears(0);
	scope.years.unshift('年');
	scope.months = ['月', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
	scope.genders = [{id:'男', name : '男'}, {id:'女', name : '女'}, {id:'其他', name : '其他'}];
	scope.backupMember={};
	scope.picurl='';
	scope.provinces = angular.copy(common_provinces);
	scope.picker='';
	scope.disableBirthFlag=false;
	
	scope.points = [];
	scope.purchases = [];
	scope.products = [];
	
		scope.birth = new mui.DtPicker({
		 	type: "date",//设置日历初始视图模式 
		    beginDate: new Date(1960, 04, 25),//设置开始日期 
		    endDate: new Date(2017, 01, 01),//设置结束日期 
		 }); 
	 
		var picker = new mui.PopPicker({
			layer: 3
		}); 
		picker.setData(common_provinces);
		
	scope.openMobileBirth = function() {
		$('.birth input').blur();
		scope.birth.show(function(items) {
			console.log(items);
			$('.birth input').val(items.text);
			var  birthItems=items.text.split("-");
			scope.member.birthyear = birthItems[0];
			scope.member.birthmonth = birthItems[1];
			scope.member.birthday = birthItems[2];
		})
	};
	
	
	scope.openPickerData=function(){
		$('.picker input').blur();
		picker.show(function(items) {
			$('.picker input').val(items[0].text+items[1].text+items[2].text);

			 scope.province=items[0];
			scope.city=items[1];
			scope.district=items[2];
		})
	}
	
	scope.getDays = function() {
		var year = scope.member.birthyear, month =scope.member.birthmonth;
		var days = dateUtils.getDays(year, month);
		var array = ['日'];
		for (var i =1; i <= days; i++) {
			array.push(i);
		}
		return array;
	};
	
	scope.openTab = function(tabIndex) {
		scope.tabIndex = tabIndex;
	};
	
	var init = function() {
		loadMember();
		loadMemberPoints(1);
		loadPurchases(1);
		loadProducts(1);
	};

	var loadMember = function() {
		apiService.get("/api/member").then(function(resp){
			if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
				scope.member = resp.data.data;
				if(!scope.member.gender){
					scope.member.gender='其他';
				}
				scope.backupMember = angular.copy(scope.member);
				bindMember();
			} else {
				scope.noneMember = true;
			}
		}, function(error){
			console.log(error);
		});
		
		apiService.get("/api/name").then(function(resp){
			if (resp && resp.data && resp.data.data) {
				scope.memberName = resp.data.data;
			} else {
				// todo
			}
		}, function(error){
			console.log(error);
		});
		
		apiService.get("/api/member/img").then(function(resp){
			if (resp && resp.data && resp.data.data) {
				scope.picurl = resp.data.data;	
				console.log(resp.data.data);
			} else {
				// todo
			}
		}, function(error){
			console.log(error);
		});
	};
	
	var loadMemberPoints = function(pageIndex) {
		apiService.get("/api/point/detail?pageIndex=" + pageIndex).then(function(resp){
			if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
				var data = resp.data.data;
				scope.points = scope.points.concat(data.pointDetail);
				console.log(scope.points);
				if (data && data.page_total > data.page_index) {
					$timeout(function(){loadMemberPoints(data.page_indxe + 1);}, 5000);
				}
			} else {
				// todo
			}
		}, function(error){
			console.log(error);
		});
	};
	
	var loadPurchases = function(pageIndex) {
		apiService.get("/api/purchase?pageIndex="+pageIndex).then(function(resp){
			if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
				var data = resp.data.data;
				scope.purchases = scope.purchases.concat(data.purchases);
				console.log(scope.purchases);
				if (data && data.page_total > data.page_index) {
					$timeout(function(){loadPurchases(data.page_indxe + 1);}, 5000);
				}
//				if (scope.purchases.length == 0) {
//					scope.purchases= [{psn:'abcd', pdt:'2010-10-01', amount:1000},{psn:'abcd', pdt:'2010-10-01', amount:1000},{psn:'abcd', pdt:'2010-10-01', amount:1000},{psn:'abcasdfasdfasdfadsfasdfdd', pdt:'2010-10-01', amount:1000}];
//				}
			} else {
				// todo
			}
		}, function(error){
			console.log(error);
		});
	};
	
	var loadProducts = function(pageIndex) {
		apiService.get("/api/product?pageIndex="+pageIndex).then(function(resp){
			if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
				var data = resp.data.data;
				scope.products = scope.products.concat(data.products);
				console.log(scope.products);
				if (data && data.page_total > data.page_index) {
					$timeout(function(){loadProducts(data.page_indxe + 1);}, 5000);
				}
//				if (scope.products.length == 0) {
//					scope.products = [{purDT:'2010-10-10',productCategoryCode:'adfa',productCategoryDesc:'asdfasdasdfasdfasdfasdff', regStatus:0}, {purDT:'2010-10-10',productCategoryCode:'adfasdfasdfasdfa',productCategoryDesc:'asdfasdf', regStatus:0}];
//				}
			} else {
				// todo
			}
		}, function(error){
			console.log(error);
		});
	};

	var bindMember = function() {
		if((scope.member.birthyear||scope.member.birthyear>0)&&(scope.member.birthmonth||scope.member.birthmonth>0)&&(scope.member.birthday||scope.member.birthday>0)){
			scope.disableBirthFlag=true;
			$('#birthDiv').unbind("click"); 
		}
		if (!scope.member.birthyear || scope.member.birthyear <= 0) {
			scope.member.birthyear = '年';
		}
		if (!scope.member.birthmonth || scope.member.birthmonth <= 0) {
			scope.member.birthmonth = '月';
		}
		if (!scope.member.birthday || scope.member.birthday <= 0) {
			scope.member.birthday = '日';
		}
		
		
		scope.member.fullBirthday =scope.member.birthyear + '-' + (scope.member.birthmonth < 10 ? ('0'+scope.member.birthmonth) : scope.member.birthmonth) + '-' + (scope.member.birthday < 10 ? ('0'+scope.member.birthday) : scope.member.birthday);
		
		scope.picker=((!scope.member.address1)?'':scope.member.address1)+''+((!scope.member.address2)?'':scope.member.address2)+''+((!scope.member.address3)?'':scope.member.address3);
		bindProvince();
		calculateTotalPoint();
	};
	
	var bindProvince = function() {
		if (scope.member && scope.member.address1) {
			scope.provinces.forEach(function(province){
				if (province && province.text == scope.member.address1) {
					scope.province = province;
					if (scope.member.address2) {
						scope.province.children.forEach(function(city){
							if (city && city.text == scope.member.address2) {
								scope.city = city;
								if (scope.member.address3) {
									scope.city.children.forEach(function(district){
										if (district && district.text == scope.member.address3) {
											scope.district = district;
											return false;
										}
									});
								}
								return false;
							}
						});
					}
					return false;
				}
			});
		}
	};

	var calculateTotalPoint = function() {
		var total = 0;
		if (scope.member && scope.member.points && scope.member && scope.member.points.length) {
			scope.member.points.forEach(function(point){
				if (point && point.totalActivePoints) {
					total += point.totalActivePoints;
				}
			})
		}
		scope.total = total;
	};
	
	scope.saveMember = function() {
		if (scope.noneMember) {
			showErrorMsg("请先完成注册或绑定");
			return;
		}
		var message = scope.checkMember();
		if(message){
			showErrorMsg(message);
			return;
		}
		var member = {
			tel : scope.member.tel,
			name : scope.member.name,
			gender : $("#gender").val(),		
			dob : getDob(),
			address1 : scope.province.text,
			address2 : scope.city.text,
			address3 : scope.district.text,
			address4 : (scope.member.address4 ? scope.member.address4 : ''),
			email : (scope.member.email ? scope.member.email : '')
		};
		console.log(member);
		apiService.put("/api/member", member).then(function(resp){
			if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
				loadMember();
				showMsg("保存信息成功");
			} else {
				// todo
				if (resp && resp.data && resp.data.meta && resp.data.meta.errors && resp.data.meta.errors.length && resp.data.meta.errors[0]
				&& resp.data.meta.errors[0].msg) {
					showErrorMsg(resp.data.meta.errors[0].msg);
				} else {
					showErrorMsg("系统正忙，请稍后再试");
				}
				
			}
			$('.alert button').click(function(){
				window.location.href = "https://siemens.ews.m.jaeapp.com/turntable/"+$("#stid").val();
			});
		}, function(error){
			console.log(error);
			showErrorMsg("系统正忙，请稍后再试");
		});
	};

	scope.checkMember = function() {
//		if(!scope.member.tel){
//			return "请完善手机号码";
//		}
		if(!scope.member.name){
			return "请完善姓名";
		}
		if(!scope.member.gender||scope.member.gender=='其他'){
			return "请完善称谓";
		}
		if(!scope.member.birthyear || !scope.member.birthmonth|| !scope.member.birthday||scope.member.birthyear=='年' || scope.member.birthmonth=='月'|| scope.member.birthday=='日'){
			return "请完善生日信息";
		}
			
		if(!scope.province ||!scope.province.text ||!scope.city || !scope.city.text || !scope.district || !scope.district.text){
			return "请完善省市区";
		}
		if (scope.member.email && !checkMail(scope.member.email)) {
				return "无效的邮箱";
		}
		return null;
	};
	
	scope.resetMember = function() {
		scope.member = angular.copy(scope.backupMember);
		bindMember();
	};
	
	scope.registeProducts = function() {
		var promises = [];
		if (scope.products.length){
			var products = [];
			scope.products.forEach(function(product){
				if (product.checked) {
					products.push(product)
				}
			});
			if (products.length) {
				if (!scope.member || !scope.member.tel) {
					$('.alert-error button').click(function(){
						if (!$('.alert-error').hasClass('hide')) {
							$('.alert-error').addClass('hide');
						}
						window.location.href = $("#redirecturl").val();
					});
					showErrorMsg("请先完善个人信息");
					return;
				}
				products.forEach(function(product){
					promises.push(apiService.put("/api/register/"+product.lcs_id));
				});
				$q.all(promises).then(function(resp, error){
					console.log(resp);
					var messageHtml = "";
					products.forEach(function(product, i){
						var v = resp[i];
						if (v && v.data && v.data.meta.success) {
							product.regStatus = v.data.data.regStatus;
							messageHtml += product.productCategoryCode + " 注册成功<br>";
							showMsg(messageHtml);
						} else {
							var msg = '系统正忙';
							if (v && v.data && v.data.meta && v.data.meta.errors && v.data.meta.errors.length && v.data.meta.errors[0]
								&& v.data.meta.errors[0].msg) {
								msg = v.data.meta.errors[0].msg;
							} 
							messageHtml += product.productCategoryCode + " 注册失败：" + msg + "<br>";
							showErrorMsg(messageHtml);
						}
						product.checked = false;
					});
					
				})
			} else {
				showErrorMsg("请先选择要注册的产品");
			}
		} else {
			showErrorMsg("请先选择要注册的产品");
		}
		
	};
	
	var checkMail=function(szMail){ 
		var szReg=/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/; 
		var bChk=szReg.test(szMail); 
		return bChk; 
	};
	
	scope.cancelProducts = function() {
		if (scope.products && scope.products.length) {
			scope.products.forEach(function(product){
				if (product.regStatus != 1) {
					product.checked = false;
				}
			});
		}
	};
	
	var getDob = function() {
		var birthyear = scope.member.birthyear;
		var birthmonth = scope.member.birthmonth;
		var birthday = scope.member.birthday;
		return birthyear + '-' + birthmonth  +'-' + birthday;
	};
	
	var showMsg = function(msg) {
		$("#sucMsg").html(msg);
		if ($('.alert').hasClass('hide')) {
			$('.alert').removeClass('hide');
		}
	};
	
	var showErrorMsg = function(msg) {
		$("#failMsg").html(msg);
		if ($('.alert-error').hasClass('hide')) {
			$('.alert-error').removeClass('hide');
		}
	};
	
	init();
	
}]);


$('.icon').click(function(e) {
	if (!$(this).hasClass('select')) {
		$(this).addClass('select')
	} else {
		$(this).removeClass('select')
	}
});

$('.alert button').click(function() {
	if (!$('.alert').hasClass('hide')) {
		$('.alert').addClass('hide');
	}
});

$('.alert-error button').click(function() {
	if (!$('.alert-error').hasClass('hide')) {
		$('.alert-error').addClass('hide');
	}
});

$('.product-body .button-body button:last-child').click(function() {
	$('.product-body .icon').removeClass('select');
});

